//调用摄像头 麦克风
export async function callCamera(video) {
  const constraints = { audio: false, video: { facingMode: 'user' } }

  try {
    //mediaDevices只有安全上下文可以使用
    await navigator.mediaDevices
      .getUserMedia(constraints)
      .then(function (mediaStream) {
        video.srcObject = mediaStream
        video.onloadedmetadata = function () {
          video.play()
        }
      })
      .catch(function (err) {
        console.log(err.name + ': ' + err.message)
      })
  } catch (error) {
    console.log(error)
  }
}
// 屏幕捕捉
export async function screenCapture(video) {
  let captureStream = null

  const displayMediaOptions: any = {
    video: {
      displaySurface: 'browser'
    },
    audio: {
      suppressLocalAudioPlayback: false
    },
    preferCurrentTab: false,
    selfBrowserSurface: 'exclude',
    systemAudio: 'include',
    surfaceSwitching: 'include',
    monitorTypeSurfaces: 'include'
  }

  try {
    captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions)

    video.srcObject = captureStream
    video.onloadedmetadata = function () {
      video.play()
    }
  } catch (err) {
    console.error(`Error: ${err}`)
  }
  return captureStream
}
/**
 * 元素视频流生成文件
 * @param {(HTMLCanvasElement|HTMLMediaElement|MediaStream)} el 媒体元素或者媒体流
 * @param {Number} lengthInMS 视频毫秒数
 */
export async function getVideo(el, lengthInMS) {
  let stream = el instanceof MediaStream ? el : el.captureStream()
  let recorder = new MediaRecorder(stream)
  let recordedChunks = []

  recorder.ondataavailable = (event) => recordedChunks.push(event.data)
  recorder.start()

  let stopped = new Promise((resolve, reject) => {
    recorder.onstop = resolve
    recorder.onerror = (event: any) => reject(event.name)
  })

  function wait(delayInMS) {
    return new Promise((resolve) => setTimeout(resolve, delayInMS))
  }

  let recorded = wait(lengthInMS).then(() => {
    if (recorder.state === 'recording') {
      recorder.stop()
    }
  })

  await Promise.all([stopped, recorded])

  let recordedBlob = new Blob(recordedChunks, {
    type: MediaRecorder.isTypeSupported('video/webm;codecs=h264')
      ? 'video/webm;codecs=h264'
      : 'video/webm'
  })
  let url = URL.createObjectURL(recordedBlob)
  let a = document.createElement('a')
  a.href = url
  a.download = MediaRecorder.isTypeSupported('video/webm;codecs=h264') ? 'video.mp4' : 'video.webm'
  a.click()
  URL.revokeObjectURL(url)
}
